package org.example.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class FileServiceImpl implements FileService {

    /**
     * 文件上传
     *
     * @param file
     */
    @Override
    public String UploadFile(MultipartFile file) throws IOException {
        if (file == null) return "文件不能为空";
        LocalDateTime currentDate = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String uuid = UUID.randomUUID().toString();
        String filePath = "/uploads/" + currentDate.format(formatter) +"/" +uuid + "/";
        File dir = new File("D:/OOS" +filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName  = file.getOriginalFilename();
        String completeFilePath = filePath + fileName;
        // 文件保存
        File f = new File("D:/OOS" +completeFilePath);
        file.transferTo(f);
        return "http://192.168.22.1:5003" + completeFilePath;
    }
}
